package com.lzw.common.interceptor;



import com.alibaba.fastjson.JSON;
import com.lzw.bean.User;
import com.lzw.common.bean.Client;
import com.lzw.common.bean.LoginInfo;
import com.lzw.common.config.LoginConfig;
import com.lzw.common.tool.CookieTool;
import com.lzw.common.tool.DesTool;
import com.lzw.common.tool.StringTool;
import com.lzw.service.UserService;
import com.lzw.service.impl.UserServiceImpl;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 * Created by 林志伟 on 2017/6/19.
 */

public class LoginInterceptor implements HandlerInterceptor {





    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //获取bean,解决无法自动注入问题
        BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(httpServletRequest.getServletContext());
        //            登录相关配置信息
        LoginConfig loginConfig= (LoginConfig) factory.getBean("loginConfig");


        CookieTool cookieTool=new CookieTool(httpServletRequest,httpServletResponse);
        String user_info=cookieTool.get(StringTool.md5(loginConfig.getCookiekey()));
        System.out.println("登录信息:"+user_info);

        if(user_info!=null){
            String logininfostr=DesTool.getInstance().decrypt(user_info);
            LoginInfo loginInfo= JSON.parseObject(logininfostr,LoginInfo.class);
            //查询当前用户信息



            UserService userService = (UserService) factory.getBean("userService");

            User user =userService.find(loginInfo.getUser_id());
            Client client=new Client();
            client.setUser(user);
            client.setIp(httpServletRequest.getRemoteAddr());
            client.setLogin_time(loginInfo.getLogin_time());

            httpServletRequest.setAttribute("client",client);

            return true;
        }
//        重定向到登录页面
        httpServletResponse.sendRedirect("/login");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
